var quIndex = 0, quLeftIndex = 0;// 问题序号

// 从题库中选择的试题
var questionMationList = new Array();

// 要删除的行选项ID列表
var deleteRowList = new Array();

// 要删除的列选项ID列表（用于矩阵题）
var deleteColumnList = new Array();

// 知识点选择必备参数
var schoolKnowledgeCheckType = 2;// 知识点选择类型：1.单选schoolKnowledgeMation；2.多选schoolKnowledgeMationList
var schoolKnowledgeMationList = new Array();

layui.config({
    base: basePath,
    version: skyeyeVersion
}).extend({
    window: 'js/winui.window'
}).define(['window', 'jquery', 'winui', 'validate', 'fileUpload'], function (exports) {
    winui.renderColor();
    layui.use(['form', 'jqueryUI'], function (form) {
        var index = parent.layer.getFrameIndex(window.name);
        var $ = layui.$,
            form = layui.form,
            element = layui.element;

        var svTag = 2;// 表示题目是问卷题还是题库中题

        $("#_basemodel").html(_basemodelSchool);
        $("#_rectanglemodel").html(_rectanglemodelSchool);
        $("#_auxiliarymodel").html(_auxiliarymodelSchool);
        $("body").append(_varioustemplatesSchool);

        var loadPageJson;

        initPageJson();

        //获取试卷信息
        function initPageJson(callback) {
            AjaxPostUtil.request({
                url: schoolBasePath + "queryDirectoryById",
                params: { id: parent.rowId },
                pagination: false,
                type: 'json',
                callback: function (json) {
                    json.total = 1;
                    $.each(json.rows, function (i, item) {
                        item.saveTag = 1;
                    });
                    loadPageJson = json;
                    if (typeof (callback) == "function") {
                        callback();
                    } else {
                        initPage();
                    }
                }
            });
        }

        function initPage() {
            showGrid({
                id: "dw_body",
                data: loadPageJson,
                pagination: false,
                template: getFileContent('tpl/examdesign/examDesignBean.tpl'),
                ajaxSendLoadBefore: function (hdb, json) {
                    $.each(json.rows, function (i, item) {
                        if (isNull(item.id)) {
                            item.id = getRandomValueToString();
                            item.noQuId = 1;
                        }
                        // 设置知识点数量
                        if (!isNull(item.knowledgeIds)) {
                            var knowledgeIds = item.knowledgeIds.split(',');
                            item.questionKnowledge = knowledgeIds; // 用于模板显示知识点数量
                        }
                    });
                    hdb.registerHelper("showIndex", function (v1, options) {
                        return parseInt(v1) + 1;
                    });

                    hdb.registerHelper('eq', function (v1, v2) {
                        return v1 === v2;
                    });

                    hdb.registerHelper("showQuestionIndex", function (v1, options) {
                        if (v1 == '16' || v1 == '17') {
                        } else {
                            quIndex++;
                            return quIndex;
                        }
                    });

                    hdb.registerHelper("showQuestionLeftIndex", function (v1, options) {
                        if (v1 == '16' || v1 == '17') {
                        } else {
                            quLeftIndex++;
                            return quLeftIndex;
                        }
                    });

                    hdb.registerHelper("showParamInt02", function (v1, options) {
                        var str = "";
                        for (var i = 1; i <= v1; i++) {
                            str += "<td>" + i + "</td>";
                        }
                        return str;
                    });

                    hdb.registerHelper('compare1', function (v1, v2, options) {
                        if (v1 == v2) {
                            return options.fn(this);
                        } else {
                            return options.inverse(this);
                        }
                    });

                    hdb.registerHelper('showQuestion', function (v1, i, options) {
                        switch (v1) {
                            case 1://1单选题radio
                                return new Handlebars.SafeString(getDataUseHandlebars($("#radioTemplate").html(), json.rows[i]));
                                break;
                            case 2://2多选题checkbox
                                return new Handlebars.SafeString(getDataUseHandlebars($("#checkBoxTemplate").html(), json.rows[i]));
                                break;
                            case 3://3填空题fillblank
                                return new Handlebars.SafeString(getDataUseHandlebars($("#fillblankTemplate").html(), json.rows[i]));
                                break;
                            case 4://4多项填空题multi-fillblank
                                return new Handlebars.SafeString(getDataUseHandlebars($("#multiFillblankTemplate").html(), json.rows[i]));
                                break;
                            case 8://8评分题score
                                return new Handlebars.SafeString(getDataUseHandlebars($("#scoreTemplate").html(), json.rows[i]));
                                break;
                            case 9://9排序题orderby
                                return new Handlebars.SafeString(getDataUseHandlebars($("#orderbyTemplate").html(), json.rows[i]));
                                break;
                            case 11://11矩阵单选题chen-radio
                                return new Handlebars.SafeString(getDataUseHandlebars($("#chenRadioTemplate").html(), json.rows[i]));
                                break;
                            case 12://12矩阵填空题chen-fbk
                                return new Handlebars.SafeString(getDataUseHandlebars($("#chenFbkTemplate").html(), json.rows[i]));
                                break;
                            case 13://13矩阵多选题chen-checkbox
                                return new Handlebars.SafeString(getDataUseHandlebars($("#chenCheckboxTemplate").html(), json.rows[i]));
                                break;
                            case 16://16分页pagetag
                                return new Handlebars.SafeString(getDataUseHandlebars($("#pagetagTemplate").html(), json.rows[i]));
                                break;
                            case 17://17段落paragraph
                                return new Handlebars.SafeString(getDataUseHandlebars($("#paragraphTemplate").html(), json.rows[i]));
                                break;
                            case 18://18矩阵评分题chen-score
                                return new Handlebars.SafeString(getDataUseHandlebars($("#chenScoreTemplate").html(), json.rows[i]));
                                break;
                        }
                    });

                    //右侧设计目录显示
                    hdb.registerHelper('compareShowLeft', function (v1, options) {
                        if (v1 != '16' && v1 != '17') {
                            return options.fn(this);
                        } else {
                            return options.inverse(this);
                        }
                    });

                    hdb.registerHelper('compare2', function (v1, v2, options) {
                        if (v1 == v2) {
                            return 'display: none;';
                        } else {
                            return '';
                        }
                    });

                    hdb.registerHelper("cellCount001", function (v1, options) {
                        var str = "";
                        var width = 600 / v1;
                        for (var i = 1; i <= v1; i++) {
                            str += '<td width="' + width + 'px">' +
                                '<input type="radio"><label style="width:' + width + 'px;" class="editAble quCoOptionEdit">{{optionName}}</label>' +
                                '<input type="text" class="optionInpText" style="{{#compare2 isNote 0}}{{/compare2}}" />' +
                                '<div class="quItemInputCase">' +
                                '<input type="hidden" name="quItemId" value="{{id}}"><input type="hidden" name="quItemSaveTag" value="1">' +
                                '<input type="hidden" name="isNote" value="{{isNote}}">' +
                                '<input type="hidden" name="checkType" value="{{checkType}}">' +
                                '<input type="hidden" name="isRequiredFill" value="{{isRequiredFill}}">' +
                                '</div>' +
                                '</td>';
                        }
                        str += '<div class="emptyTd"></div>';
                        return str;
                    });

                    hdb.registerHelper("cellCount002", function (v1, options) {
                        var str = "";
                        var width = 600 / v1;
                        for (var i = 1; i <= v1; i++) {
                            str += '<td width="' + width + 'px">' +
                                '<input type="checkbox"><label style="width:' + width + 'px;" class="editAble quCoOptionEdit">{{optionName}}</label>' +
                                '<input type="text" class="optionInpText" style="{{#compare2 isNote 0}}{{/compare2}}" />' +
                                '<div class="quItemInputCase">' +
                                '<input type="hidden" name="quItemId" value="{{id}}"><input type="hidden" name="quItemSaveTag" value="1">' +
                                '<input type="hidden" name="isNote" value="{{isNote}}">' +
                                '<input type="hidden" name="checkType" value="{{checkType}}">' +
                                '<input type="hidden" name="isRequiredFill" value="{{isRequiredFill}}">' +
                                '</div>' +
                                '</td>';
                        }
                        str += '<div class="emptyTd"></div>';
                        return str;
                    });
                },
                ajaxSendAfter: function (json) {
                    // 初始化地址区域
                    loadAddr();

                    // 加载拖拽事件
                    loadDrag();

                    // 加载答案数据
                    loadAnswer(json);

                    matchingLanguage();
                    form.render();

                    // 绑定变动
                    bindQuHoverItem();

                    // 初始化右侧目录
                    resetQuLeftItem(); // 确保在页面加载时调用

                    $("#dwSurveyName").click(function () {
                        editAble($(this));
                        return false;
                    });
                    $("#dwSurveyNoteEdit").click(function () {
                        editAble($(this));
                        return false;
                    });
                }
            });
        }

        /**
         * 加载答案
         */
        function loadAnswer(json) {
            $.each(json.rows, function (m, bean) {
                // 1.设置视频，音频，图片等的tab页选中
                var qBodyItem = $("input[name='quId'][value='" + bean.id + "']").parents(".surveyQuItemBody");
                var layuiTab = qBodyItem.find(".layui-tab");
                layuiTab.find('.layui-tab-title li').eq(bean.fileType).addClass('layui-this').siblings().removeClass('layui-this');
                layuiTab.find('.layui-tab-item').eq(bean.fileType).addClass('layui-show').siblings().removeClass('layui-show');
                // 2.是否允许拍照/上传图片
                if (isNull(bean.whetherUpload)) {
                    bean.whetherUpload = 2;
                }
                qBodyItem.find("input:radio[name='whetherUpload" + bean.id + "'][value='" + bean.whetherUpload + "']").attr("checked", true);
                // 3.设置试题附件
                pageLoadAfter(bean.id, bean.fileType, bean.fileUrl);
                // 4.加载答案
                var quType = bean.quTypeName;
                if (quType === "CHENCHECKBOX") {
                    var answer = qBodyItem.find(".quCoItem table.quCoChenTable tr input.chenCheckBoxInput");
                    var isDefaultAnswer = isJsonFormat(bean.isDefaultAnswer) ? JSON.parse(bean.isDefaultAnswer) : [];
                    var columuLength = qBodyItem.find(".quCoItem table.quCoChenTable tr td.quChenColumnTd").length;
                    var xIndex = 0;
                    var yIndex = 1;
                    $.each(answer, function (i) {
                        if (i % columuLength == 0) {
                            xIndex++;
                            yIndex = 1;
                        } else {
                            yIndex++;
                        }
                        var _this = this;
                        $.each(isDefaultAnswer, function (j, item) {
                            if (item.x == xIndex && item.y == yIndex) {
                                $(_this).prop("checked", item.value);
                            }
                        });
                    });
                } else if (quType === "CHENRADIO") {
                    var answer = qBodyItem.find(".quCoItem table.quCoChenTable tr input.chenRadioInput");
                    var isDefaultAnswer = isJsonFormat(bean.isDefaultAnswer) ? JSON.parse(bean.isDefaultAnswer) : [];
                    var columuLength = qBodyItem.find(".quCoItem table.quCoChenTable tr td.quChenColumnTd").length;
                    var xIndex = 0;
                    var yIndex = 1;
                    $.each(answer, function (i) {
                        if (i % columuLength == 0) {
                            xIndex++;
                            yIndex = 1;
                        } else {
                            yIndex++;
                        }
                        var _this = this;
                        $.each(isDefaultAnswer, function (j, item) {
                            if (item.x == xIndex && item.y == yIndex) {
                                $(_this).prop("checked", item.value);
                            }
                        });
                    });
                } else if (quType === "CHENSCORE") {
                    var answer = qBodyItem.find(".quCoItem table.quCoChenTable tr select.quChenScoreSelect");
                    var isDefaultAnswer = isJsonFormat(bean.isDefaultAnswer) ? JSON.parse(bean.isDefaultAnswer) : [];
                    var columuLength = qBodyItem.find(".quCoItem table.quCoChenTable tr td.quChenColumnTd").length;
                    var xIndex = 0;
                    var yIndex = 1;
                    $.each(answer, function (i) {
                        if (i % columuLength == 0) {
                            xIndex++;
                            yIndex = 1;
                        } else {
                            yIndex++;
                        }
                        var _this = this;
                        $.each(isDefaultAnswer, function (j, item) {
                            if (item.x == xIndex && item.y == yIndex) {
                                $(_this).val(item.value);
                            }
                        });
                    });
                } else if (quType === "CHENFBK") {
                    var answer = qBodyItem.find(".quCoItem table.quCoChenTable tr input.questionChenColumnValue");
                    var isDefaultAnswer = isJsonFormat(bean.isDefaultAnswer) ? JSON.parse(bean.isDefaultAnswer) : [];
                    var columuLength = qBodyItem.find(".quCoItem table.quCoChenTable tr td.quChenColumnTd").length;
                    var xIndex = 0;
                    var yIndex = 1;
                    $.each(answer, function (i) {
                        if (i % columuLength == 0) {
                            xIndex++;
                            yIndex = 1;
                        } else {
                            yIndex++;
                        }
                        var _this = this;
                        $.each(isDefaultAnswer, function (j, item) {
                            if (item.x == xIndex && item.y == yIndex) {
                                $(_this).val(item.value);
                            }
                        });
                    });
                }
                // 说明是从题库中导入的试题
                if (bean.tag == 1) {
                    qBodyItem.find("input[name='quId'][value='" + bean.id + "']").val("");
                    bean.id = "";
                }
                // 设置知识点数量
                if (!isNull(bean.knowledgeIds)) {
                    var knowledgeIds = bean.knowledgeIds.split(',');
                    qBodyItem.find(".quKnowledgeInfo").text(knowledgeIds.length);
                }
            });
            form.render();
        }

        var exam = {
            "RADIO": deleteRadioOption, // 删除单选题选项
            "CHECKBOX": deleteCheckboxOption, // 删除多选题选项
            "SCORE": deleteScoreOption, // 删除评分题选项
            "ORDERBY": deleteOrderquOption, //删除排序题选项
            "MULTIFILLBLANK": deleteMultiFillblankOption, // 删除多行天空题选项
            "CHENRADIO": deleteChenOption, // 删除矩阵题
            "CHENCHECKBOX": deleteChenOption, // 删除矩阵题
            "CHENFBK": deleteChenOption, // 删除矩阵题
            "CHENSCORE": deleteChenOption, // 删除矩阵题
            "SAVEQUS": saveQus, // 保存题目信息
            // 添加类型转换函数
            convertQuType: function (quType) {
                // 数字到字符串的映射
                var quTypeMap = {
                    1: 'RADIO',
                    2: 'CHECKBOX',
                    3: 'FILLBLANK',
                    4: 'MULTIFILLBLANK',
                    8: 'SCORE',
                    9: 'ORDERBY',
                    11: 'CHENRADIO',
                    12: 'CHENFBK',
                    13: 'CHENCHECKBOX',
                    16: 'PAGETAG',
                    17: 'PARAGRAPH',
                    18: 'CHENSCORE'
                };

                // 如果是数字或数字字符串，转换为对应的类型字符串
                if (!isNaN(quType)) {
                    return quTypeMap[parseInt(quType)] || quType;
                }
                // 如果已经是字符串类型，直接返回
                return quType;
            }
        };

        // 注册到 layui
        layui.exam = exam;

        // 删除题目
        $("body").on("click", ".dwQuDelete", function () {
            var quBody = $(this).parents(".surveyQuItemBody");
            layer.confirm("确认要删除此题吗？", { icon: 3, title: '删除题目' }, function (index) {
                layer.close(index);
                var quId = quBody.find("input[name='quId']").val();
                if (!isNull(quId)) {
                    quBody.data("deleteTag", true);
                    quBody.hide("slow", function () {
                        $(this).parent().remove();
                        // 重置序号
                        resetQuItem();
                        // 重置左侧设计目录序号
                        resetQuLeftItem();
                    })

                } else {
                    quBody.hide("slow", function () {
                        $(this).parent().remove();
                        // 重置序号
                        resetQuItem();
                        // 重置左侧设计目录序号
                        resetQuLeftItem();
                    });
                }
            });
            return false;
        });

        /**
         * 删除矩陈单选题选项
         */
        function deleteChenOption() {
            var optionParent = null;
            var quItemBody = $(curEditObj).parents(".surveyQuItemBody");

            // 判断是删除行还是列
            if ($(curEditObj).parents("td.quChenColumnTd")[0]) {
                // 删除列
                optionParent = $(curEditObj).parents("td.quChenColumnTd");
                var columnIndex = $(optionParent).index();
                var quCoChenTable = quItemBody.find("table.quCoChenTable");
                var columnCount = quCoChenTable.find("tr:first td").length;

                // 检查是否只剩最后一列（减1是因为第一列是标题列）
                if (columnCount <= 2) {
                    winui.window.msg("至少需要保留一个选项", { icon: 2, time: 2000 });
                    return;
                }

                // 记录要删除的选项ID
                var quOptionId = $(optionParent).find("input[name='quItemId']").val();
                if (quOptionId != "" && quOptionId != "0") {
                    deleteColumnList.push(quOptionId);
                }

                // 删除该列所有单元格
                quCoChenTable.find("tr").each(function () {
                    $(this).find("td").eq(columnIndex).remove();
                });

            } else {
                // 删除行
                optionParent = $(curEditObj).parents("tr.quChenRowTr");
                if (!optionParent.length) {
                    optionParent = $(curEditObj).parents("tr");
                }

                var rowCount = quItemBody.find("table.quCoChenTable tr").length;

                // 检查是否只剩最后一行（减1是因为第一行是标题行）
                if (rowCount <= 2) {
                    winui.window.msg("至少需要保留一个选项", { icon: 2, time: 2000 });
                    return;
                }

                // 记录要删除的选项ID
                var quOptionId = $(optionParent).find("input[name='quItemId']").val();
                if (quOptionId != "" && quOptionId != "0") {
                    deleteRowList.push(quOptionId);
                }

                // 直接从UI移除整行
                $(optionParent).remove();
            }
        }

        // 知识点选择
        $("body").on("click", ".knowledgeQuLogic", function () {
            var _this = this;
            var oldKnowIds = $(_this).attr("knowledgeIds");
            schoolKnowledgeMationList = new Array();
            if (!isNull(oldKnowIds)) {
                $.each(oldKnowIds.split(','), function (i, item) {
                    schoolKnowledgeMationList.push({
                        id: item
                    });
                });
            }
            knowledgeReturnList = [].concat(schoolKnowledgeMationList);
            _openNewWindows({
                url: "../../tpl/schoolKnowledgePoints/schoolKnowledgePointsChoose.html",
                title: "知识点选择",
                pageId: "schoolKnowledgePointsChoose",
                area: ['90vw', '90vh'],
                callBack: function (refreshCode) {
                    if (refreshCode == '0') {
                        schoolKnowledgeMationList = [].concat(knowledgeReturnList);
                        var strIds = new Array();
                        $.each(schoolKnowledgeMationList, function (i, item) {
                            strIds.push(item.id);
                        });
                        $(_this).attr("knowledgeIds", strIds.toString());
                        $(_this).find(".quKnowledgeInfo").text(schoolKnowledgeMationList.length);
                        // 设置题目为编辑，可以进行保存
                        var quItemBody = $(_this).parents(".surveyQuItemBody");
                        quItemBody.find("input[name='saveTag']").val(0);
                    }
                }
            });
        });

        // 取消
        $("body").on("click", "#cancle", function () {
            parent.layer.close(index);
        });

        // 题库选择试题
        $("body").on("click", "#questionBankBtn", function () {
            questionMationList = [];
            allSave();
            _openNewWindows({
                url: "../../tpl/schoolQuestionBank/schoolQuestionBankChoose.html",
                title: "试题选择",
                pageId: "schoolQuestionBankChoose",
                area: ['90vw', '90vh'],
                callBack: function (refreshCode) {
                    initPageJson(function () {
                        quIndex = 0, quLeftIndex = 0;
                        if (loadPageJson && loadPageJson.rows && loadPageJson.bean && loadPageJson.bean.questionLeftList) {
                            $.each(questionMationList, function (i, item) {
                                // 加载试题数据
                                item.saveTag = 0;
                                item.orderById = (loadPageJson.rows.length + 1);
                                loadPageJson.rows.push(item);
                                // 加载右侧列表数据
                                loadPageJson.bean.questionLeftList.push({
                                    quType: item.quType,
                                    quTitle: item.quTitle,
                                    fraction: item.fraction
                                });
                            });
                            initPage();
                        } else {
                            // 如果必要的对象未初始化，则初始化它们
                            if (!loadPageJson) {
                                loadPageJson = {};
                            }
                            if (!loadPageJson.rows) {
                                loadPageJson.rows = [];
                            }
                            if (!loadPageJson.bean) {
                                loadPageJson.bean = {};
                            }
                            if (!loadPageJson.bean.questionLeftList) {
                                loadPageJson.bean.questionLeftList = [];
                            }

                            // 现在可以安全地添加数据
                            $.each(questionMationList, function (i, item) {
                                item.saveTag = 0;
                                item.orderById = (loadPageJson.rows.length + 1);
                                loadPageJson.rows.push(item);
                                loadPageJson.bean.questionLeftList.push({
                                    quType: item.quType,
                                    quTitle: item.quTitle,
                                    fraction: item.fraction
                                });
                            });
                            initPage();
                        }
                    });
                    form.render();
                }
            });
        });

        // 保存
        $("body").on("click", "#saveBtn", function () {
            allSave();
        });

        function allSave() {
            curEditCallback();
            dwCommonDialogHide();
            resetQuItemHover(null);
            // 构建试卷基本信息
            var examData = {
                id: loadPageJson.bean.id || "",
                belongId: parent.rowId,
                surveyName: $("#dwSurveyName").text(),
                surveyNote: $("#dwSurveyNoteEdit").text(),
                questionMation: [],
                viewAnswer: loadPageJson.bean.viewAnswer || 0, // 默认值为0
                schoolId: loadPageJson.bean.schoolId || "", // 默认值为空字符串
                facultyId: loadPageJson.bean.facultyId || "",
                majorId: loadPageJson.bean.majorId || "",
                gradeld: loadPageJson.bean.gradeld || "",
                classId: loadPageJson.bean.classId || "",
                surveyModel: loadPageJson.bean.surveyModel,
                surveyState: loadPageJson.bean.surveyState,
                realStartTime: loadPageJson.bean.realStartTime || "",
                realEndTime: loadPageJson.bean.realEndTime || "",
                semesterId: loadPageJson.bean.semesterId || "",
                subjectId: loadPageJson.bean.subjectId || "",
                fraction: loadPageJson.bean.fraction || 0,
                whetherDelete: loadPageJson.bean.whetherDelete || 1,
                readerList: loadPageJson.bean.readerMationList.map(reader => reader.id).join(','), // 阅卷人列表的 id，用逗号拼接
            };

            // 调用 saveQus 方法收集所有题目的参数
            saveQus(function (questionMation) {
                // 遍历题目，处理删除逻辑
                questionMation = questionMation.map(question => {
                    if (question.deleteTag) {
                        // 如果是删除的题目，移除 belongId
                        delete question.belongId;
                    }
                    return question;
                });
                examData.questionMation = questionMation; // 将题目参数添加到试卷数据中
                examData.questionMation = JSON.stringify(examData.questionMation);
                examData.whetherDelete = 1;
                saveExam(examData); // 调用统一接口保存试卷
            });

        }

        function saveExam(examData) {
            AjaxPostUtil.request({
                url: schoolBasePath + "writeExamDirectory", // 统一接口
                params: examData,
                type: 'json',
                callback: function (json) {
                    if (json.bean) {
                        parent.refreshCode = '0'; // 设置刷新码
                        winui.window.msg("保存成功", { icon: 1, time: 2000 });
                    } else {
                        winui.window.msg("保存失败：" + json.message, { icon: 2, time: 2000 });
                    }
                }
            });
        }

        /**
         * 保存标记说明
         * saveTag  标记本题有无变动
         * quTitleSaveTag  标记题标题变动
         * quItemSaveTag 标记题选项变动
         * 0=表示有变动，未保存
         * 1=表示已经保存同步
         */
        function saveQus(callback) {
            var questionMation = [];

            // 定义题型映射表
            var quTypeMap = {
                // 数字到字符串的映射
                1: 'RADIO',
                2: 'CHECKBOX',
                3: 'FILLBLANK',
                4: 'MULTIFILLBLANK',
                8: 'SCORE',
                9: 'ORDERBY',
                11: 'CHENRADIO',
                12: 'CHENFBK',
                13: 'CHENCHECKBOX',
                16: 'PAGETAG',
                18: 'CHENSCORE',
                // 字符串到数字的映射
                'RADIO': 1,
                'CHECKBOX': 2,
                'FILLBLANK': 3,
                'MULTIFILLBLANK': 4,
                'SCORE': 8,
                'ORDERBY': 9,
                'CHENRADIO': 11,
                'CHENFBK': 12,
                'CHENCHECKBOX': 13,
                'PAGETAG': 16,
                'CHENSCORE': 18
            };

            // 遍历所有题目
            $("#dwSurveyQuContent .surveyQuItemBody").each(function () {
                var quItemBody = $(this);
                var quType = quItemBody.find("input[name='quType']").val();

                // 统一处理 quType
                var quTypeStr, quTypeNum;

                if (!isNaN(parseInt(quType))) {
                    // 如果 quType 是数字字符串，转换为数字
                    quTypeNum = parseInt(quType);
                    quTypeStr = quTypeMap[quTypeNum]; // 根据数字获取对应的题型字符串
                } else if (quTypeMap[quType]) {
                    // 如果 quType 是字符串形式的题型名称（如 "RADIO"），转换为数字
                    quTypeStr = quType;
                    quTypeNum = quTypeMap[quType]; // 根据字符串获取对应的数字
                } else {
                    winui.window.msg("未知题型：" + quType, { icon: 2, time: 2000 });
                }
                var quId = quItemBody.find("input[name='quId']").val(); // 获取题目 ID
                // 判断是新增还是编辑
                var isEdit = !isNull(quId); // 如果 quId 存在，则是编辑；否则是新增

                // 根据题型调用对应的保存方法
                var questionData;
                switch (quTypeStr) {
                    case 'RADIO':
                        questionData = saveRadio(quItemBody, isEdit);
                        break;
                    case 'CHECKBOX':
                        questionData = saveCheckbox(quItemBody, isEdit);
                        break;
                    case 'FILLBLANK':
                        questionData = saveFillblank(quItemBody, isEdit);
                        break;
                    case 'SCORE':
                        questionData = saveScore(quItemBody, isEdit);
                        break;
                    case 'ORDERBY':
                        questionData = saveOrderqu(quItemBody, isEdit);
                        break;
                    case 'MULTIFILLBLANK':
                        questionData = saveMultiFillblank(quItemBody, isEdit);
                        break;
                    case 'CHENRADIO':
                    case 'CHENCHECKBOX':
                    case 'CHENFBK':
                    case 'CHENSCORE':
                        questionData = saveChen(quItemBody, isEdit);
                        break;
                    case 'PAGETAG':
                        questionData = savePagetag(quItemBody, isEdit);
                        break;
                    default:
                        winui.window.msg("未知题型：" + quTypeStr, { icon: 2, time: 2000 });
                        return;
                }

                // 将转换后的 quType 添加到 questionData
                questionData.quType = quTypeNum;
                // 将题目参数对象添加到 questionMation 数组
                questionMation.push(questionData);
            });


            // 调用回调函数
            if (typeof callback === "function") {
                callback(questionMation);
            }
        }

        /**
         * 公共获取提交参数部分
         */
        function getCommonParams(quItemBody) {
            var fileUrl = "";
            var tabIndex = quItemBody.find(".layui-tab").find(".layui-tab-title").find(".layui-this").index();
            var checkNameIn = getNameCheckIn(quItemBody);
            var whetherUpload = quItemBody.find("input[name='whetherUpload" + checkNameIn + "']:checked").val() || '2'; // 默认值为2
            
            // 获取题目标题
            var quTitle = '';
            if (quItemBody.find("input[name='quType']").val() == '16') {  // 如果是分页题目
                quTitle = '分页标记';  // 设置默认标题
            } else {
                quTitle = quItemBody.find(".quCoTitleEdit").html() || '';  // 如果其他题目没有标题，至少设置为空字符串
            }

            if (tabIndex != 0 && tabIndex >= 0) {
                fileUrl = quItemBody.find(".layui-tab-content").find(".layui-show").find(".upload").find("input[type='hidden'][name='upload']").attr("oldurl");
                if (isNull(fileUrl)) {
                    winui.window.msg('请上传文件.', { icon: 2, time: 2000 });
                    throw err = new Error('请上传文件');
                }
            } else {
                fileUrl = "";
            }
            if (tabIndex == -1) {
                tabIndex = 0;
            }
            return {
                id: quItemBody.find("input[name='quId']").val(),
                hv: quItemBody.find("input[name='hv']").val(),
                randOrder: quItemBody.find("input[name='randOrder']").val(),
                cellCount: quItemBody.find("input[name='cellCount']").val(),
                quTitle: JSON.stringify(quTitle).slice(1, -1),
                quType: quItemBody.find("input[name='quType']").val(),
                fraction: isNull(quItemBody.find("input[name='fraction']").val()) ? 0 : quItemBody.find("input[name='fraction']").val(),
                knowledgeIds: quItemBody.find(".knowledgeQuLogic").attr("knowledgeIds") || "",
                fileUrl: fileUrl,
                fileType: tabIndex,//试题类型，0.默认没有，1.视频，2.音频，3.图片
                whetherUpload: whetherUpload,//是否允许拍照/上传图片选中，1.是，2.否
                tag: svTag,// 1题库里的题，2 试卷里的题
                belongId: parent.rowId,
                orderById: quItemBody.find("input[name='orderById']").val(),
            };
        }

        /** 保存单选题 **/
        function saveRadio(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            // params.quId = quId;
            
            var data = {
                contactsAttr: quItemBody.find("input[name='contactsAttr']").val(),
                contactsField: quItemBody.find("input[name='contactsField']").val()
            };
            $.extend(data, params);
            var quItemOptions = null;
            if (data.hv == 3) {
                //还有是table的情况需要处理
                quItemOptions = quItemBody.find(".quCoItem table.tableQuColItem tr td");
            } else {
                quItemOptions = quItemBody.find(".quCoItem li.quCoItemUlLi");
            }
            var radioTd = [];
            $.each(quItemOptions, function (i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    // 是否是默认答案  1.是  2.否
                    var isDefaultAnswer = 2;
                    if ($(this).find("input[type='radio']").is(':checked')) {
                        isDefaultAnswer = 1
                    }
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        isNote: $(this).find(".quItemInputCase input[name='isNote']").val(),
                        checkType: $(this).find(".quItemInputCase input[name='checkType']").val(),
                        isRequiredFill: $(this).find(".quItemInputCase input[name='isRequiredFill']").val(),
                        orderById: i,
                        quId: quId  // 添加题目ID到每个选项
                    };
                    // 如果是编辑，传入 optionId
                    // if (isEdit) {
                    //     s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    // }
                    radioTd.push(s);
                }
                //更新 字母 title标记到选项上.
                $(this).addClass("quOption_" + i);
            });
            data.radioTd = JSON.stringify(radioTd);
            return data;
        }

        /**
         * 删除单选题选项
         */
        function deleteRadioOption() {
            var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
            var hv = quItemBody.find("input[name='hv']").val();
            var optionParent = null;
            if (hv == 3) {
                optionParent = $(curEditObj).parents("td");
                // 检查表格中的选项数量
                if (quItemBody.find(".quCoItem td").length <= 1) {
                    winui.window.msg('至少需要保留一个选项', { icon: 2, time: 2000 });
                    return false;
                }
            } else {
                optionParent = $(curEditObj).parents("li.quCoItemUlLi");
                // 检查列表中的选项数量
                if (quItemBody.find(".quCoItem li.quCoItemUlLi").length <= 1) {
                    winui.window.msg('至少需要保留一个选项', { icon: 2, time: 2000 });
                    return false;
                }
            }
            // 直接移除选项
            $(optionParent).remove();
        }

        /** 保存多选题 **/
        function saveCheckbox(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            // params.quId = quId;
            
            var data = {
                contactsAttr: quItemBody.find("input[name='contactsAttr']").val(),
                contactsField: quItemBody.find("input[name='contactsField']").val()
            };
            $.extend(data, params);
            var quItemOptions = null;
            if (data.hv == 3) {
                //还有是table的情况需要处理
                quItemOptions = quItemBody.find(".quCoItem table.tableQuColItem tr td");
            } else {
                quItemOptions = quItemBody.find(".quCoItem li.quCoItemUlLi");
            }
            var checkboxTd = [];
            $.each(quItemOptions, function (i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    // 是否是默认答案  1.是  2.否
                    var isDefaultAnswer = 2;
                    if ($(this).find("input[type='checkbox']").is(':checked')) {
                        isDefaultAnswer = 1
                    }
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        isNote: $(this).find(".quItemInputCase input[name='isNote']").val(),
                        checkType: $(this).find(".quItemInputCase input[name='checkType']").val(),
                        isRequiredFill: $(this).find(".quItemInputCase input[name='isRequiredFill']").val(),
                        isDefaultAnswer: isDefaultAnswer,
                        orderById: i,
                        quId: quId  // 添加题目ID到每个选项
                    };
                    // 如果是编辑，传入 optionId
                    if (isEdit) {
                        s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    }
                    checkboxTd.push(s);
                }
                //更新 字母 title标记到选项上.
                $(this).addClass("quOption_" + i);
            });
            data.checkboxTd = JSON.stringify(checkboxTd);

            return data;
        }

        /**
         * 删除多选题选项
         */
        function deleteCheckboxOption() {
            var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
            var hv = quItemBody.find("input[name='hv']").val();
            var optionParent = null;
            if (hv == 3) {
                optionParent = $(curEditObj).parents("td");
                // 检查表格中的选项数量
                if (quItemBody.find(".quCoItem td").length <= 1) {
                    winui.window.msg('至少需要保留一个选项', { icon: 2, time: 2000 });
                    return false;
                }
            } else {
                optionParent = $(curEditObj).parents("li.quCoItemUlLi");
                // 检查列表中的选项数量
                if (quItemBody.find(".quCoItem li.quCoItemUlLi").length <= 1) {
                    winui.window.msg('至少需要保留一个选项', { icon: 2, time: 2000 });
                    return false;
                }
            }
            // 直接移除选项
            $(optionParent).remove();
        }

        function delQuOptionCallBack(optionParent) {
            var quItemBody = $(optionParent).parents(".surveyQuItemBody");
            var quType = quItemBody.find("input[name='quType']").val();
            if (quType == "CHECKBOX" || quType == "RADIO") {
                var hv = quItemBody.find("input[name='hv']").val();
                if (hv == 3) {
                    //emptyTd
                    var optionTr = $(optionParent).parents("tr");
                    var optionNextTr = optionTr.next();
                    if (optionNextTr[0]) {
                        //则后面还有是中间选项，则删除，再依次后面的td往前移动
                        $(optionParent).remove();
                        moveTabelTd(optionNextTr);
                    } else {
                        //非中间选项，删除-再添加一个空td
                        $(optionParent).remove();
                        movePareseLastTr(optionTr);
                    }
                } else {
                    optionParent.remove();
                }
            } else if (quType == "CHENRADIO" || quType == "CHENCHECKBOX" || quType == "CHENFBK" || quType == "CHENSCORE") {
                var quCoChenTable = optionParent.parents("table.quCoChenTable");
                var optionParentClass = optionParent.attr("class");
                if (optionParentClass.indexOf("Column") >= 0) {
                    var removeTrs = quCoChenTable.find("tr:gt(0)");
                    $.each(removeTrs, function () {
                        $(this).find("td:last").remove();
                    });
                    optionParent.remove();
                } else {
                    optionParent.parent().remove();
                }
            } else {
                optionParent.remove();
            }
            dwCommonEditHide();
            bindQuHoverItem();
        }

        function moveTabelTd(nextTr) {
            if (nextTr[0]) {
                var prevTr = nextTr.prev();
                var nextTds = nextTr.find("td");
                $(nextTds.get(0)).appendTo(prevTr);
                //判断当前next是否是最后一个，是则：判断如果没有选项，则删除tr,如果有选项，则填一个空td
                var nextNextTr = nextTr.next();
                if (!nextNextTr[0]) {
                    movePareseLastTr(nextTr);
                }
                moveTabelTd($(nextTr).next());
            }
        }

        function movePareseLastTr(nextTr) {
            var editAbles = nextTr.find(".editAble");
            if (editAbles[0]) {
                //有选项，则补充一个空td
                var editAbleTd = editAbles.parents("td");
                editAbleTd.clone().prependTo(nextTr);
                nextTr.find("td").last().html("<div class='emptyTd'></div>");
            } else {
                nextTr.remove();
            }
        }

        /** 保存填空题 **/
        function saveFillblank(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            params.quId = quId;
            
            var data = {
                answerInputWidth: quItemBody.find("input[name='answerInputWidth']").val(),
                answerInputRow: quItemBody.find("input[name='answerInputRow']").val(),
                contactsAttr: quItemBody.find("input[name='contactsAttr']").val(),
                contactsField: quItemBody.find("input[name='contactsField']").val(),
                checkType: quItemBody.find("input[name='checkType']").val(),
                isDefaultAnswer: quItemBody.find("input[class='quFillblankAnswerInput']").val()
            };
            $.extend(data, params);
            return data;
        }

        /** 保存评分题 **/
        function saveScore(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            // params.quId = quId;
            
            var data = {
                paramInt01: quItemBody.find("input[name='paramInt01']").val(),
                paramInt02: quItemBody.find("input[name='paramInt02']").val()
            };
            $.extend(data, params);
            //评分题选项td
            var quItemOptions = quItemBody.find(".quCoItem table.quCoItemTable tr td.quOptionEditTd");
            var scoreTd = [];
            $.each(quItemOptions, function (i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        orderById: i,
                        quId: quId  // 添加题目ID到每个选项
                    };
                    // 如果是编辑，传入 optionId
                    if (isEdit) {
                        s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    }
                    scoreTd.push(s);
                }
                //更新 字母 title标记到选项上.
                $(this).addClass("quOption_" + i);
            });
            data.scoreTd = JSON.stringify(scoreTd);
            return data;
        }

        /**
         * 删除评分Score选项
         */
        function deleteScoreOption() {
            var optionParent = null;
            optionParent = $(curEditObj).parents("tr.quScoreOptionTr");

            // 检查是否只剩最后一个选项
            var quItemBody = $(optionParent).parents(".surveyQuItemBody");
            var scoreOptions = quItemBody.find("tr.quScoreOptionTr");
            if (scoreOptions.length <= 1) {
                layer.msg("至少需要保留一个选项", { icon: 2, time: 2000 });
                return;
            }

            // 记录要删除的选项ID
            var quOptionId = $(optionParent).find("input[name='quItemId']").val();
            if (quOptionId != "" && quOptionId != "0") {
                deleteRowList.push(quOptionId);
            }

            // 直接从UI移除
            $(optionParent).remove();
        }

        /** 保存排序题 **/
        function saveOrderqu(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            // params.quId = quId;
            
            var data = {};
            $.extend(data, params);
            //评分题选项td
            var quItemOptions = quItemBody.find(".quCoItem .quOrderByLeft  li.quCoItemUlLi");
            var orderByTd = [];
            $.each(quItemOptions, function (i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        orderById: i,
                        quId: quId  // 添加题目ID到每个选项
                    };
                    // 如果是编辑，传入 optionId
                    if (isEdit) {
                        s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    }
                    orderByTd.push(s);
                }
                $(this).addClass("quOption_" + i);
            });
            data.orderByTd = JSON.stringify(orderByTd);
            return data;
        }

        /**
         * 删除排序选项
         */
        function deleteOrderquOption() {
            var optionParent = null;
            optionParent = $(curEditObj).parents("li.quCoItemUlLi");

            // 检查是否只剩最后一个选项
            var quItemBody = $(optionParent).parents(".surveyQuItemBody");
            var orderOptions = quItemBody.find("li.quCoItemUlLi");
            if (orderOptions.length <= 1) {
                layer.msg("至少需要保留一个选项", { icon: 2, time: 2000 });
                return;
            }

            // 记录要删除的选项ID
            var quOptionId = $(optionParent).find("input[name='quItemId']").val();
            if (quOptionId != "" && quOptionId != "0") {
                deleteRowList.push(quOptionId);
            }

            // 同时删除右侧序号表格中对应的行
            var orderTableTr = quItemBody.find(".quOrderByRight table.quOrderByTable tr").eq($(optionParent).index());
            $(orderTableTr).remove();

            // 直接从UI移除
            $(optionParent).remove();

            // 重新排序右侧序号
            var quOrderByTable = quItemBody.find(".quOrderByRight table.quOrderByTable");
            refquOrderTableTdNum(quOrderByTable);
        }

        /** 保存分页标记 **/
        function savePagetag(quItemBody, isEdit) {
            var data = {};
            $.extend(data, getCommonParams(quItemBody));
            return data;
        }

        /** 保存段落题 **/
        function saveParagraph(quItemBody, callback) {
            var data = {};
            $.extend(data, getCommonParams(quItemBody));
            // 逻辑选项
            var list = [].concat(getLogic(quItemBody));
            data.logic = JSON.stringify(list);
            return data;
        }

        /** 新保存多项填空题 **/
        function saveMultiFillblank(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            // params.quId = quId;
            
            var data = {
                paramInt01: quItemBody.find("input[name='paramInt01']").val(),
                paramInt02: quItemBody.find("input[name='paramInt02']").val()
            };
            $.extend(data, params);
            // 评分题选项td
            var quItemOptions = quItemBody.find(".quCoItem table.mFillblankTable tr");
            var multifillblankTd = [];
            $.each(quItemOptions, function (i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        isDefaultAnswer: $(this).find("input[class='multiFillBlank']").val(),
                        orderById: i,
                        quId: quId  // 添加题目ID到每个选项
                    };
                    // 如果是编辑，传入 optionId
                    if (isEdit) {
                        s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    }
                    multifillblankTd.push(s);
                }
                // 更新 字母 title标记到选项上.
                $(this).addClass("quOption_" + i);
            });
            data.multifillblankTd = JSON.stringify(multifillblankTd);
            return data;
        }

        /**
         * 删除多项填空题选项
         */
        function deleteMultiFillblankOption() {
            var optionParent = null;
            optionParent = $(curEditObj).parents("tr.mFillblankTableTr");

            // 检查是否只剩最后一个选项
            var quItemBody = $(optionParent).parents(".surveyQuItemBody");
            var fillblankOptions = quItemBody.find("tr.mFillblankTableTr");
            if (fillblankOptions.length <= 1) {
                layer.msg("至少需要保留一个选项", { icon: 2, time: 2000 });
                return;
            }

            // 记录要删除的选项ID
            var quOptionId = $(optionParent).find("input[name='quItemId']").val();
            if (quOptionId != "" && quOptionId != "0") {
                deleteRowList.push(quOptionId);
            }

            // 直接从UI移除
            $(optionParent).remove();
        }

        /** 保存矩阵题 **/
        function saveChen(quItemBody, isEdit) {
            var quId = quItemBody.find("input[name='quId']").val();
            var params = getCommonParams(quItemBody);
            
            // 添加 quId 到参数中
            // params.quId = quId;
            
            // 矩阵列选项td
            var quColumnOptions = quItemBody.find(".quCoItem table.quCoChenTable tr td.quChenColumnTd");
            // 矩阵行选项td
            var quRowOptions = quItemBody.find(".quCoItem table.quCoChenTable tr td.quChenRowTd");
            
            // 检查列选项名称是否为空
            var hasEmptyOption = false;
            quColumnOptions.each(function() {
                var optionName = $(this).find("label.quCoOptionEdit").html().trim();
                if(isNull(optionName)) {
                    hasEmptyOption = true;
                    return false;
                }
            });
            
            // 检查行选项名称是否为空
            quRowOptions.each(function() {
                var optionName = $(this).find("label.quCoOptionEdit").html().trim();
                if(isNull(optionName)) {
                    hasEmptyOption = true;
                    return false;
                }
            });
            
            if(hasEmptyOption) {
                winui.window.msg("选项名称不能为空", {icon: 2, time: 2000});
                throw new Error("选项名称不能为空");
            }
            
            // 继续原有的保存逻辑...
            var columnTd = [];
            $.each(quColumnOptions, function(i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        visibility: 1,
                        orderBy: i,
                        quId: quId  // 添加题目ID到每个列选项
                    };
                    // 如果是编辑，传入 optionId
                    if (isEdit) {
                        s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    }
                    columnTd.push(s);
                }
                // 更新 字母 title标记到选项上.
                $(this).addClass("quColumnOption_" + i);
            });
            params.columnTd = JSON.stringify(columnTd);
            // 矩阵行选项td
            var rowTd = [];
            $.each(quRowOptions, function (i) {
                var quItemSaveTag = $(this).find(".quItemInputCase input[name='quItemSaveTag']").val();
                if (quItemSaveTag == 0) {
                    var s = {
                        optionName: encodeURI($(this).find("label.quCoOptionEdit").html()),
                        visibility: 1,
                        orderBy: i,
                        quId: quId  // 添加题目ID到每个行选项
                    };
                    // 如果是编辑，传入 optionId
                    if (isEdit) {
                        s.optionId = $(this).find(".quItemInputCase input[name='quItemId']").val();
                    }
                    rowTd.push(s);
                }
                // 更新 字母 title标记到选项上.
                $(this).addClass("quRowOption_" + i);
            });

            // 答案
            if (params.quType === "CHENCHECKBOX") {
                var answer = quItemBody.find(".quCoItem table.quCoChenTable tr input.chenCheckBoxInput");
                var isDefaultAnswer = new Array();
                var columuLength = quColumnOptions.length;
                var xIndex = 0;
                var yIndex = 1;
                $.each(answer, function (i) {
                    if (i % columuLength == 0) {
                        xIndex++;
                        yIndex = 1;
                    } else {
                        yIndex++;
                    }
                    var s = {
                        x: xIndex,
                        y: yIndex,
                        value: $(this).prop("checked")
                    };
                    isDefaultAnswer.push(s);
                });
                params.isDefaultAnswer = JSON.stringify(isDefaultAnswer);
            } else if (params.quType === "CHENRADIO") {
                var answer = quItemBody.find(".quCoItem table.quCoChenTable tr input.chenRadioInput");
                var isDefaultAnswer = new Array();
                var columuLength = quColumnOptions.length;
                var xIndex = 0;
                var yIndex = 1;
                $.each(answer, function (i) {
                    if (i % columuLength == 0) {
                        xIndex++;
                        yIndex = 1;
                    } else {
                        yIndex++;
                    }
                    var s = {
                        x: xIndex,
                        y: yIndex,
                        value: $(this).prop("checked")
                    };
                    isDefaultAnswer.push(s);
                });
                params.isDefaultAnswer = JSON.stringify(isDefaultAnswer);
            } else if (params.quType === "CHENSCORE") {
                var answer = quItemBody.find(".quCoItem table.quCoChenTable tr select.quChenScoreSelect");
                var isDefaultAnswer = new Array();
                var columuLength = quColumnOptions.length;
                var xIndex = 0;
                var yIndex = 1;
                $.each(answer, function (i) {
                    if (i % columuLength == 0) {
                        xIndex++;
                        yIndex = 1;
                    } else {
                        yIndex++;
                    }
                    var s = {
                        x: xIndex,
                        y: yIndex,
                        value: $(this).val()
                    };
                    isDefaultAnswer.push(s);
                });
                params.isDefaultAnswer = JSON.stringify(isDefaultAnswer);
            } else if (params.quType === "CHENFBK") {
                var answer = quItemBody.find(".quCoItem table.quCoChenTable tr input.questionChenColumnValue");
                var isDefaultAnswer = new Array();
                var columuLength = quColumnOptions.length;
                var xIndex = 0;
                var yIndex = 1;
                $.each(answer, function (i) {
                    if (i % columuLength == 0) {
                        xIndex++;
                        yIndex = 1;
                    } else {
                        yIndex++;
                    }
                    var s = {
                        x: xIndex,
                        y: yIndex,
                        value: $(this).val()
                    };
                    isDefaultAnswer.push(s);
                });
                params.isDefaultAnswer = JSON.stringify(isDefaultAnswer);
            }

            params.rowTd = JSON.stringify(rowTd);
            return params;
        }

        //分数变化事件
        $("body").on("change", "#dwBodyLeftContent .exam-fraction", function () {
            fractionChange($(this));
        });
        $("body").on("keyup", "#dwBodyLeftContent .exam-fraction", function () {
            fractionChange($(this));
        });

        //分数变化
        function fractionChange(_this) {
            var quId = _this.attr("toid");//问题id
            var value = _this.val();//内容
            if ((/^(\+|-)?\d+$/.test(value)) && value > 0) {
                var questionCase;
                
                // Check if this is a position-based ID (starts with q_)
                if (quId && quId.startsWith("q_")) {
                    // Get the question index from the position ID (q_1 -> 1)
                    var questionIndex = parseInt(quId.substring(2)) - 1;
                    // Find the question at that index position
                    var questions = $("#dwSurveyQuContent .surveyQuItemBody").filter(function() {
                        var quType = $(this).find("input[name='quType']").val();
                        return quType != "PAGETAG" && quType != "PARAGRAPH" && quType != '16' && quType != '17';
                    });
                    questionCase = $(questions[questionIndex]).find("input[name='fraction']").parent();
                } else {
                    // Use the traditional quId lookup
                    questionCase = $("#dwSurveyQuContent").find("input[name='quId'][value='" + quId + "']").parent();
                }
                
                // Update the fraction value
                if (questionCase && questionCase.length > 0) {
                    questionCase.find("input[name='fraction']").val(value);
                    questionCase.find("input[name='saveTag']").val("0");
                }
            } else {
                notify("请输入正整数分数！", 800);
            }
        }

        function pageLoadAfter(quId, tabIndex, fileUrl) {
            if (isNull(quId)) {
                quId = getRandomValueToString();
                $("#questionVedio").attr("id", "questionVedio" + quId);
                $("#questionAudio").attr("id", "questionAudio" + quId);
                $("#questionPicture").attr("id", "questionPicture" + quId);
            }
            // 初始化视频上传
            $("#questionVedio" + quId).upload({
                "action": reqBasePath + "common003",
                "data-num": "1",
                "data-type": vedioType,
                "uploadType": 16,
                "data-value": (tabIndex == 1 && !isNull(fileUrl)) ? fileUrl : "",
                "function": function (_this, data) {
                    show(_this, data);
                }
            });

            // 初始化音频上传
            $("#questionAudio" + quId).upload({
                "action": reqBasePath + "common003",
                "data-num": "1",
                "data-type": audioType,
                "uploadType": 16,
                "data-value": (tabIndex == 2 && !isNull(fileUrl)) ? fileUrl : "",
                "function": function (_this, data) {
                    show(_this, data);
                }
            });

            // 初始化图片上传
            $("#questionPicture" + quId).upload({
                "action": reqBasePath + "common003",
                "data-num": "1",
                "data-type": imageType,
                "uploadType": 16,
                "data-value": (tabIndex == 3 && !isNull(fileUrl)) ? fileUrl : "",
                "function": function (_this, data) {
                    show(_this, data);
                }
            });
        }

    });

});